//
//  ShopDetailViewController.m
//  随便点
//
//  Created by MWJ on 15/4/2.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "ShopDetailViewController.h"
#import "ViewController.h"
#import "BuyCell.h"
#import "AppDelegate.h"
#import "GoodsList.h"
#import "OrderCheckViewController.h"
#import "CleanCheckViewController.h"
#import "ShopViewController.h"
#import "LoginViewController.h"
#define xhl @"http://www.51anys.com:8080/waimaiwang/order/saveOrder"

#define waimai  @"0";
#define waimai2  @"2";

@interface ShopDetailViewController (){
    NSDictionary *shopDic;    //店铺字典
    NSDictionary *TypeDic;      //类型字典
    NSMutableArray *TypeArray;    //类型数组
    NSMutableArray *GoodsListArray;     //物品数组
    NSMutableArray *TypeListArray;      //类型列表数组
    NSMutableArray *listarray;      //菜品列表数组
    NSString *str1;     //接口拼接：网址前缀
    NSString *str2;     //接口拼接：店铺ID
    NSString *str3;     //接口拼接：店铺类型
    NSString *str4;     //接口拼接：分类ID
    NSString *str5;     //接口拼接：跳过信息条数
    NSString *str6;     //接口拼接：完整接口
    AppDelegate *delegate;
    UIAlertView *_alert;
    NSString *xhlstr;
    NSString *aaa;
    NSString *xiche;
    NSMutableArray *smallArray;
    NSMutableArray *smallArray1;
    NSMutableArray *smallArray2;
    NSMutableArray *smallArray3;

}

@property (nonatomic,strong)RefreshControl * refreshControl;

@end

@implementation ShopDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    delegate =(AppDelegate *)[[UIApplication sharedApplication]delegate];
    delegate.detailsVC = self;
    
    //tableView 顶端不出现空白
    self.automaticallyAdjustsScrollViewInsets=NO;
    //默认跳过条数为0
    str5 = @"0";
    smallArray = [NSMutableArray array];
    _array = [NSMutableArray array];
    TypeArray=[NSMutableArray array];   //类型数组
    TypeListArray=[NSMutableArray array];   //类型列表数组
    listarray = [NSMutableArray array]; //菜品列表数组
    GoodsListArray=[NSMutableArray array];
    
    self.tableViewRight.dataSource = nil;
    self.tableViewLeft.dataSource = nil;
    
    //左边tableview请求数据
    [self setTypeList];
    
    //设置导航栏的title为该店店名
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 80.0f, 30.0f)];//初始化图片视图控件
    UIColor *navigationColor= [UIColor colorWithRed:100/255.0 green:200/255.0 blue:0/255.0 alpha:1];
    button.backgroundColor=navigationColor;
    button.contentMode = UIViewContentModeScaleAspectFit;//设置内容样式,通过保持长宽比缩放内容适应视图的大小,任何剩余的区域的视图的界限是透明的。
    xiche = @"【随便点】洗车服务";
    if (delegate.ViewC.ButtonChoose == 4) {
        [button setTitle:[NSString stringWithFormat:@"%@",xiche] forState:UIControlStateNormal];
    }else{
    [button setTitle:[NSString stringWithFormat:@"%@",delegate.ShopName] forState:UIControlStateNormal];
    }
    self.navigationItem.titleView = button; //设置导航栏的titleView为imageView
    [button addTarget:self action:@selector(titleClick) forControlEvents:UIControlEventTouchUpInside];
    
    //上拉刷新
    _refreshControl=[[RefreshControl alloc] initWithScrollView:self.tableViewRight delegate:self];
    _refreshControl.topEnabled=NO;
    _refreshControl.bottomEnabled=YES;
    
    [self.tableViewRight reloadData];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 上拉刷新

- (void)refreshControl:(RefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection)direction
{
    if (direction==RefreshDirectionTop)
    {
        
        [GoodsListArray removeAllObjects];
        
    }
    else if (direction==RefreshDirectionBottom)
    {
        
    }
    
    __weak typeof(self)weakSelf=self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf=weakSelf;
        [strongSelf reloadData];
    });
    
}

-(void)reloadData
{
    
    str5=[NSString stringWithFormat:@"%d",[str5 intValue]+10];
    
    [self setUpNotes];
    
    if (self.refreshControl.refreshingDirection==RefreshingDirectionTop)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionTop];
    }
    else if (self.refreshControl.refreshingDirection==RefreshingDirectionBottom)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionBottom];
        
    }
    
    str5=[NSString stringWithFormat:@"%d",[str5 intValue]-10];
    [self.tableViewRight reloadData];
}



#pragma mark - title的点击事件

-(void)titleClick{
    
    
    ShopViewController *shopVC=[[ShopViewController alloc]initWithNibName:@"ShopViewController" bundle:nil];
    [self.navigationController pushViewController:shopVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -- cell的行数

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //右边tableview的行数
    if (tableView ==self.tableViewRight) {
        if (GoodsListArray==nil) {
            return 1;
        }else{
        return GoodsListArray.count;
        }
        
    }
    //左边tableview的行数
    else{
        if (TypeListArray == nil) {
            return 1;
        }else{
        return TypeListArray.count;
        }
    }
}

#pragma mark -- cell的高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //右边tableview的高度
    if (tableView == self.tableViewRight) {
        return 100;
    }
    //左边tableview的高度
    else{
        return 30;
    }
}


#pragma mark -- cell的内容加载

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //右边tableview内容的加载
    if (tableView ==self.tableViewRight) {
        UINib *nib = [UINib nibWithNibName:@"BuyCell" bundle:nil];
        [self.tableViewRight registerNib:nib forCellReuseIdentifier:@"BuyCell"];
        static NSString *cellIdentifier=@"BuyCell";
        BuyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (GoodsListArray == nil||GoodsListArray.count == 0) {
            NSLog(@"没有商品");
        }else{
        GoodsList *gl=GoodsListArray[indexPath.row];
        cell.BuyName.text = [NSString stringWithFormat:@"%@",gl.GoodsName];
        cell.BuyPrice.text=[NSString stringWithFormat:@"%@",gl.GoodsPrice];
        cell.BuyPrice.textColor=[UIColor redColor];
        cell.SalesCount.text=[NSString stringWithFormat:@"%@",gl.GoodsSalesCount];
        cell.caipingid = [NSString stringWithFormat:@"%@",gl.cpidl];
        //cell的某一行
        cell.indexpath = indexPath.row;
        //菜品的点击数量
        cell.BuyCount.text = _BigArray[_index][indexPath.row][@"数量"];
        //如果菜品的个数为0，“减号按钮隐藏”
        if ([_BigArray[_index][indexPath.row][@"数量"]  isEqual: @"0"]) {
            cell.reduceButton.hidden = YES;
        }else{
            cell.reduceButton.hidden = NO;
        }
        NSString *haha=@"http://www.51anys.com:8080/waimaiwang/resources/";
        NSString *hehe=[NSString stringWithFormat:@"%@",gl.GoodsImage];
        NSString *string=[NSString stringWithFormat:@"%@%@",haha,hehe];
        NSURL *url=[NSURL URLWithString:string];
        cell.BuyImage.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        self.indexpath = indexPath.row;

        //已选数量
        self.Label1.text = [NSString stringWithFormat:@"%d",_total];
        //总金额
        self.Label2.text = [NSString stringWithFormat:@"%.2f", _AllPrice];
        }
        return cell;
    }
    //左边tableview内容的加载
    else{
        static NSString *cellIdentifier=@"cell";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (cell == nil) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellIdentifier];
        }
        
        GoodsList *typeList=TypeListArray[indexPath.row];
        //店铺下类型的分类显示
        cell.textLabel.text=[NSString stringWithFormat:@"%@",typeList.TypeName];

        //分类显示字体为黑色
        cell.textLabel.textColor=[UIColor blackColor];
        
        // 文字靠左
        cell.textLabel.textAlignment=UITextAlignmentLeft;
        
        return cell;
    }
    
}
-(void)photoTapped{
    self.small_view.hidden = NO;
    CGFloat imgW = self.small_scrollPic.bounds.size.width;
    CGFloat imgH = self.small_scrollPic.bounds.size.height-80;
    for (int i=0; i<smallArray.count; i++) {
        // UIImageView
        NSString *qz = @"http://www.51anys.com:8080/waimaiwang/resources/";
        NSString *imgName1 = [NSString stringWithFormat:@"%@%@",qz,smallArray[i]];
        NSURL *url=[NSURL URLWithString:imgName1];
        self.imgName = [[UIImageView alloc]init];
        self.imgName.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        // 如果保持imageView里面的image不变形
        //设置UIImageView的对象的以下两个属性，可以图片不变形且充满图片框为前提进行填充。
        self.imgName.clipsToBounds = YES;
        self.imgName.contentMode = UIViewContentModeScaleAspectFill;
        // y是0,x是一张连着一张
        self.imgName.frame = CGRectMake(i*imgW, 30, imgW, imgH);
        // 将所有的图片添加到scrollView
        UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.small_scrollPic.bounds.size.width, self.small_scrollPic.bounds.size.height)];
        [v addSubview:self.imgName];
        [self.small_scrollPic addSubview:v];
    }
    // 0代表高度方向不滚动
    self.small_scrollPic.contentSize = CGSizeMake(smallArray.count*imgW, 0);
    // 按scrollView的宽度分页
    self.small_scrollPic.pagingEnabled = YES;
}

#pragma mark - cell的点击事件，根据左边点击事件加载右边tableview数据

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    if (tableView == self.tableViewLeft) {
        //代理初始化
        delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
        //获取左边tableview的每一行类型ID
        GoodsList *Good=TypeListArray[indexPath.row];
        delegate.Typeid=[NSString stringWithFormat:@"%@",Good.TypeId];
        _index = indexPath.row;
        [GoodsListArray removeAllObjects];
        //右边tableview请求数据
        [self setUpNotes];
        
        self.tableViewRight.dataSource = nil;

    }
}


#pragma mark - "选好了"按钮点击事件

- (IBAction)DoneButton:(id)sender {
    if ([delegate._id  isEqual: @""]||delegate._id == nil) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:nil, nil];
        _alert = alert;
        [alert show];
    }else{
    
    //设置按钮为半圆形
    self.ButtonDone=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    //判断是否已选择商品
    if ([self.Label1.text isEqualToString:@"0"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"至少选择一项服务项目" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        if (delegate.ViewC.ButtonChoose==4) {
        [self xuanhaole];
        // 获取到当前页面 总数量 和 总金额，传到下一个页面去
        delegate.cleanCount=self.Label1.text;
        delegate.cleanPrice=self.Label2.text;
        
    }else{
        [self xuanhaole];
        // 获取到当前页面 总数量 和 总金额，传到下一个页面去
        delegate.BuyCount=self.Label1.text;
        delegate.BuyPrice=self.Label2.text;
    }
    }
        
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        LoginViewController *lgvc = [self.storyboard instantiateViewControllerWithIdentifier:@"loginVC"];
        [self.navigationController pushViewController:lgvc animated:YES];
    }
}
-(void)xuanhaole{
    for (NSMutableArray *pjarray in _BigArray) {
        for (int i = 0; i<pjarray.count; i++) {
            if (![pjarray[i][@"数量"] isEqual:@"0"]) {
                aaa = [NSString stringWithFormat:@"%@,%@;",pjarray[i][@"商品id"],pjarray[i][@"数量"]];
                [self.array addObject:aaa];
            }
        }
    }
    NSString *straaa = @"";
    for (int j=0; j<self.array.count; j++) {
        NSString * strbbb;
        strbbb = [NSString stringWithFormat:@"%@",self.array[j]];
        straaa = [NSString stringWithFormat:@"%@%@",straaa,strbbb];
    }
    NSString *IOS = @"ios";
    NSURL *url=[NSURL URLWithString:xhl];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"shopId=%@&userId=%@&goods=%@&platform=%@",delegate.spid,delegate._id,straaa,IOS];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        xhlstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1) withObject:xhlstr waitUntilDone:YES];
        delegate.xhlddid = xhlstr;
        if (delegate.ViewC.ButtonChoose == 4) {
            CleanCheckViewController *cleanCheck=[self.storyboard instantiateViewControllerWithIdentifier:@"cleanCheck"];
            [self.navigationController pushViewController:cleanCheck animated:YES];
        }else{
        OrderCheckViewController *orderCheckVC=[self.storyboard instantiateViewControllerWithIdentifier:@"orderCheck"];
        [self.navigationController pushViewController:orderCheckVC animated:YES];
        }
    }];
}

#pragma MARK - 界面将要结束时执行代码
-(void)viewWillDisappear:(BOOL)animated{
    delegate.ViewC.ButtonChoose = 1;
}

#pragma mark - 左边tableview请求数据
-(void)setTypeList{
    
    str1 = @"http://www.51anys.com:8080/waimaiwang/good/typeList/";
    str2 = [NSString stringWithFormat:@"%@",delegate.spid];
    
    //判断上个页面的选择控制器，“推荐菜品”为1
    if (delegate.ViewC.segmentedControl.selectedSegmentIndex == 1) {
        
        //美食店ID为418
        str2 = @"418";
        str4 = [NSString stringWithFormat:@"%@%@/%@",str1,str2,@"0"];
    }
    else if (delegate.ViewC.ButtonChoose == 4){
        
        //洗车服务商店ID为420
        str2= @"420";
        str4 = [NSString stringWithFormat:@"%@%@/%@",str1,str2,@"3"];
    }
    
    //“推荐店铺”
    else{
        
        if ([delegate.splx  isEqual: @"外卖"]||[delegate.splx  isEqual: @"外卖、堂食"]) {
            str3 = waimai;   //0
        }
        else if([delegate.splx isEqual:@"便利店"]){
            str3 = waimai2;     //2
        }else{
            str3 = @"1";
        }
        
        str4 = [NSString stringWithFormat:@"%@%@/%@",str1,str2,str3];
    }
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:str4]];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        TypeDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData3) withObject:TypeDic waitUntilDone:YES];
        
        
        _BigArray = [NSMutableArray array];
        if (TypeDic.count == 0||TypeDic == nil) {
            self.tableViewLeft.hidden = YES;
            self.tableViewRight.hidden = YES;
        }else{
        for(NSDictionary *obj in TypeDic){
            GoodsList *goodsList=[[GoodsList alloc]init];
            goodsList.TypeId=obj[@"id"];
            goodsList.TypeName=obj[@"name"];
            [TypeListArray addObject:goodsList];
            
            NSMutableArray *Smallarray = [NSMutableArray array];

            [_BigArray addObject:Smallarray];
        }
        if(delegate.ViewC.segmentedControl.selectedSegmentIndex == 1){
            
            delegate.Typeid=@"1";
            
        }
        else if (delegate.ViewC.ButtonChoose == 4){
            
            //洗车服务店铺类型ID为3
            delegate.Typeid= @"3";
        }
        else
        {
            GoodsList *Good=TypeListArray[0];
            delegate.Typeid=[NSString stringWithFormat:@"%@",Good.TypeId];
        }
        
        //请求右边tableview数据
        
        [self setUpNotes];

        _index = 0;
        self.tableViewLeft.dataSource = self;
        [self.tableViewLeft reloadData];
        
        self.tableViewRight.dataSource = nil;
        
        }
        
    }];
}


#pragma mark - 右边tableview请求数据
-(void)setUpNotes{
    
    str1 = @"http://www.51anys.com:8080/waimaiwang/good/goodList";
    str2 = [NSString stringWithFormat:@"%@",delegate.spid];  //店铺ID
    str4 = [NSString stringWithFormat:@"%@",delegate.Typeid];  //类型ID
//    str5 = @"0";
    
    if (delegate.ViewC.segmentedControl.selectedSegmentIndex == 1) {
        //“美食店”店铺ID为418
        str2 = @"418";
        str6 = [NSString stringWithFormat:@"%@/%@/%@/%@/%@",str1,str2,@"0",str4,str5];
    }
    else if (delegate.ViewC.ButtonChoose == 4){
        
        //洗车服务商店ID为420
        str2 = @"420";
        
        //洗车服务类型ID为56，店铺类型ID为3
        str6 = [NSString stringWithFormat:@"%@/%@/%@/%@/%@",str1,str2,@"3",@"56",str5];
    }
    else{
        
        
        if ([delegate.splx  isEqual: @"外卖"]||[delegate.splx  isEqual: @"外卖、堂食"]) {
            str3 = waimai;      //0
        }
        else if([delegate.splx isEqual:@"便利店"]){
            str3 = waimai2;     //2
        }else{
            str3 = @"1";
        }
        
        str6 = [NSString stringWithFormat:@"%@/%@/%@/%@/%@",str1,str2,str3,str4,str5];
    }
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:str6]];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        shopDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshDataa) withObject:shopDic waitUntilDone:YES];
        listarray=shopDic[@"list"];
        for(NSDictionary *obj in listarray){
            GoodsList *goodsList=[[GoodsList alloc]init];
            goodsList.GoodsImage=obj[@"image"];
            goodsList.GoodsName=obj[@"name"];
            goodsList.GoodsSalesCount=obj[@"count"];
            goodsList.GoodsPrice=obj[@"price"];
            goodsList.cpidl = obj[@"id"];
            goodsList.guige = obj[@"remark"];
            [GoodsListArray addObject:goodsList];
            NSMutableDictionary *SmallDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:obj[@"id"],@"商品id",@"0",@"数量",nil];
            [_BigArray[_index] addObject:SmallDic];
        }
        self.tableViewRight.dataSource = self;
        [self.tableViewRight reloadData];
    }];

}

-(void)refreshData1{
    
}
-(void)refreshDataa{
    
}

-(void)refreshData3{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)small_close:(id)sender {
    self.small_view.hidden = YES;
}
@end
